#！/usr/bin/env python3
from flask import Flask, request, jsonify
import hashlib
import xml.etree.ElementTree as ET
import time
import xmltodict
from wx_to_tele import get_gif
from PIL import Image
from weixin_token import get_access_token,get_media_id
import re
import requests
from apscheduler.schedulers.background import BackgroundScheduler
from get_brakes import get_brake_energy_speed, check_input
from get_app_perform import get_performance


# 创建一个调度器
scheduler = BackgroundScheduler()
# 每 6 分钟运行一次任务
scheduler.add_job(get_gif, "interval", minutes=6)
scheduler.start()

app = Flask(__name__)
TOKEN="SYNAIRTECH"
app_id = "wx51cb64ce8378743b"
app_secret = "66eda769562e58c9221eacbcc018e364"
file_path = "images/1.png"  # 你的文件路径
media_type = "image"       # 文件类型：image, voice, video, thumb
# 验证微信服务器的请求
def check_signature(signature, timestamp, nonce):
    # token = get_access_token(app_id, app_secret)
    token = TOKEN
    # 1. 将token、timestamp、nonce三个参数进行字典序排序
    tmp_list = [token, timestamp, nonce]
    tmp_list.sort()
    # 2. 将三个参数字符串拼接成一个字符串进行sha1加密
    tmp_str = ''.join(tmp_list).encode('utf-8')
    tmp_str = hashlib.sha1(tmp_str).hexdigest()
    # 3. 比较signature与加密后的字符串是否相同
    if tmp_str == signature:
        return True
    return False

@app.route('/wechat', methods=['GET', 'POST'])
def wechat():
    signature = request.args.get('signature')
    timestamp = request.args.get('timestamp')
    nonce = request.args.get('nonce')
    echostr = request.args.get('echostr')

    # GET请求：验证微信服务器
    if request.method == 'GET':
        if check_signature(signature, timestamp, nonce):
            return echostr
        return 'Signature mismatch', 400

    # POST请求：处理微信服务器发来的消息
    if request.method == 'POST':
        print(request.data)
        if check_signature(signature, timestamp, nonce):
            xml_data = request.data
            root = ET.fromstring(xml_data)
            msg_type = root.find('MsgType').text
            from_user = root.find('FromUserName').text
            to_user = root.find('ToUserName').text

            # 处理文本消息
            if isinstance(msg_type, str) and msg_type == 'text':
                content = root.find('Content').text
                pattern1 = r'^[a-zA-Z]{4}$'
                pattern2 = r'\b(2[246][k|s|a])\b[\s,:@/,]\d+(\.\d+)?[\s,:@/,][-+]?\d+[\s,:@/,]\d+[\s,:@/,]\d+'
                if "雷达" in content:
                    res_dict = {
                    "xml": {
                        "ToUserName": from_user,
                        "FromUserName": to_user,
                        "CreateTime": int(time.time()),
                        "MsgType":  media_type,
                        "Image": {
                            "MediaId": get_media_id(get_access_token(app_id, app_secret), file_path, media_type)
                        }
                    }
                    }
                elif re.match(pattern1, content):
                    url=f'https://aviationweather.gov/cgi-bin/data/metar.php?ids={content}&hours=2&order=id%2C-obs&sep=true&taf=true'
                    response=requests.get(url)
                    wx_data=response.text
                    res_dict = {
                    "xml": {
                        "ToUserName": from_user,
                        "FromUserName": to_user,
                        "CreateTime": int(time.time()),
                        "MsgType":  'text',
                        "Content":  wx_data
                        }
                    }
                elif re.match(pattern2, content): 
                    split_pattern = r'[\s,:@/,]'
                    engine_rate = re.search(r'2[246][k|s|a]', content).group()

                    split_values = re.split(split_pattern, content)[1:]
                    split_values = [float(value) if '.' in value else int(value) for value in split_values if re.match(r'[+-]?\d+(\.\d+)?', value)]
                    weight_input=split_values[0]
                    weight_input,flag_weight=check_input(weight_input,[40, 50, 60, 70, 80])
                    temperature_input=split_values[1]
                    temperature_input,flag_temperature=check_input(temperature_input,[0, 10, 15, 20, 30, 40, 50])
                    elevation_input=split_values[2]
                    elevation_input,flag_elevation=check_input(elevation_input,[0, 5000, 10000])
                    altitude_input=split_values[3]
                    altitude_input,flag_altitude=check_input(altitude_input,[-2000, -1000, 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 13000, 14000, 14500])
                    config_approach = ['0UP', '1UP', '5UP']
                    overheat_speed,melted_speed = get_brake_energy_speed(engine_rate,weight_input,temperature_input,elevation_input)
                
                    perform={}
                    for config_approach_input in config_approach:
                        pitch= get_performance(f'data/{engine_rate}/pitch.xlsx',altitude_input, weight_input, config_approach_input)
                        N1= get_performance(f'data/{engine_rate}/N1.xlsx',altitude_input, weight_input, config_approach_input)
                        airspeed= get_performance(f'data/{engine_rate}/speed.xlsx',altitude_input, weight_input, config_approach_input)
                        perform[config_approach_input]= (pitch,N1,airspeed)
                    perform_strings = [f"{key}:{value}" for key, value in perform.items()]
                    perform_strings = '\n'.join(perform_strings)
                    
                    if flag_weight==1 or flag_temperature==1 or flag_elevation==1 or flag_altitude==1:
                        res_dict = {
                        "xml": {
                            "ToUserName": from_user,
                            "FromUserName": to_user,
                            "CreateTime": int(time.time()),
                            "MsgType":  'text',
                            "Content":f'输入数据超限，已修正为：{engine_rate,weight_input,temperature_input,elevation_input,altitude_input}\n注意区速度：{overheat_speed}\n熔塞区速度: {melted_speed}\n空不可靠对应的数据:\n{perform_strings}'
                            }
                        }
                    elif flag_weight==2 or flag_temperature==2 or flag_elevation==2 or flag_altitude==2:
                        res_dict = {
                        "xml": {
                            "ToUserName": from_user,
                            "FromUserName": to_user,
                            "CreateTime": int(time.time()),
                            "MsgType":  'text',
                            "Content":f'输入数据不合法，请按建议格式输入！'
                            }
                        }
                    else:
                        res_dict = {
                        "xml": {
                            "ToUserName": from_user,
                            "FromUserName": to_user,
                            "CreateTime": int(time.time()),
                            "MsgType":  'text',
                            "Content":f'注意区速度：{overheat_speed}\n熔塞区速度: {melted_speed}\n空不可靠对应的数据:\n{perform_strings}'
                            }
                        }

                # res_xml=xmltodict.unparse(res_dict)
                
            else:
                
                res_dict={
                "xml":
                {
                    "ToUserName":from_user,
                    "FromUserName":to_user,
                    "CreateTime":int(time.time()),
                    "MsgType":"text",
                    "Content":"请发如下格式文本:全国雷达  全球雷达 机场四字码得METAR-TAF如ZSAM"
                }
                }
            res_xml=xmltodict.unparse(res_dict)
            return res_xml
            
        return 'Invalid request', 400

if __name__ == '__main__':   
    app.run(host='0.0.0.0', port=80)